<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\product\ProductClassModel;
use App\Models\product\ProductCourseModel;
use App\Models\product\ProductModel;
use App\Models\product\ProductPlatformModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use lxs\api\ApiResponse;
use lxs\tools\Tools;

class ProductController extends Controller
{

    /**
     * 获取产品列表页面数据
     */
    public function getProductListData()
    {
        $data = request()->input();

        $query = ProductModel::with(['productPlatform', 'productCourse', 'productClass'])
            ->where('deleted_at', 0);

        if ($data['keywords'] != '') {
            $query->where('product_title', 'like', '%' . $data['keywords'] . '%');
        }

        if ($data['platform_id'] > 0) {
            $query->whereHas('productPlatform', function($q) use ($data) {
                $q->where('id', $data['platform_id']);
            });
        }

        if ($data['course_id'] > 0) {
            $query->whereHas('productCourse', function($q) use ($data) {
                $q->where('id', $data['course_id']);
            });
        }

        if ($data['dateTime'] != '') {
            foreach ($data['dateTime'] as $k => $v) {
                $data['dateTime'][$k] = (new Carbon($v))->format('Y-m-d H:i:s');
            }
            $startTime = $data['dateTime'][0];
            $endTime = $data['dateTime'][1];
            $query->whereBetween('live_time', [$startTime, $endTime]);
        }

        $lists = $query->orderBy('id', 'desc')->paginate($data['pageSize']);
        foreach ($lists as $k => $v) {
            $lists[$k]['live_time'] = Tools::timeConvert($v['live_time']);
        }

        $platform = ProductPlatformModel::get();

        $course = ProductCourseModel::get();

        return ApiResponse::apiResponseData(200, '获取商品列表数据成功', [
            'lists' => $lists,
            'platform' => $platform,
            'course' => $course,
        ]);
    }


    /**
     * 更新产品列表上下架状态
     */
    public function productUpdateStatus()
    {
        $post = request()->input();

        $product = ProductModel::find($post['id']);

        $product->is_status = $post['is_status'];

        $product->save();

        return ApiResponse::apiResponseData(200, '更新成功');
    }


    /**
     * 删除产品提交
     */
    public function productDeleteSubmit()
    {
        $post = request()->input();

        $product = ProductModel::find($post['id']);

        $product->deleted_at = 1;

        $product->save();

        return ApiResponse::apiResponseData(200, '删除成功');
    }


    /**
     * 获取产品详情表单数据
     */
    public function getProductFormData()
    {
        $product_id = request()->input('id');

        $lists = [];
        if ($product_id > 0) {
            $lists = ProductModel::find($product_id);
            $lists->live_time = (new Carbon($lists->live_time))->format('Y-m-d H:i:s');
        }

        $classData = ProductClassModel::get();

        $platformData = ProductPlatformModel::get();

        $courseData = ProductCourseModel::get();

        return ApiResponse::apiResponseData(200, '获取商品详情表单数据成功', [
            'lists' => $lists,
            'classData' => $classData,
            'platformData' => $platformData,
            'courseData' => $courseData,
        ]);
    }


    /**
     * 产品表单数据提交
     */
    public function productFormSubmit()
    {
        $post = request()->input();

        if (!filter_var($post['user_link'], FILTER_VALIDATE_URL)) {
            return ApiResponse::apiResponseData(400, '请输入正确的用户端链接');
        }
        if (!filter_var($post['lawyer_link'], FILTER_VALIDATE_URL)) {
            return ApiResponse::apiResponseData(400, '请输入正确的律师端链接');
        }
        if (!filter_var($post['share_link'], FILTER_VALIDATE_URL)) {
            return ApiResponse::apiResponseData(400, '请输入正确的分享链接');
        }
        if (!strtotime($post['live_time'])) {
            return ApiResponse::apiResponseData(400, '请输入正确的上线时间');
        }

        $post['live_time'] = Tools::timeConvert($post['live_time']);

        if (isset($post['id'])) {
            $product = ProductModel::find($post['id']);
        } else {
            $product = new ProductModel();
            $product->create_time = Carbon::now();
        }
        try {
            $product->class_id = $post['class_id'];
            $product->platform_id = $post['platform_id'];
            $product->course_id = $post['course_id'];
            $product->product_title = $post['product_title'];
            $product->product_cover = $post['product_cover'];
            $product->commission = $post['commission'];
            $product->product_intro = $post['product_intro'];
            $product->live_time = $post['live_time'];
            $product->user_link = $post['user_link'];
            $product->lawyer_link = $post['lawyer_link'];
            $product->share_link = $post['share_link'];
            $product->is_status = $post['is_status'];
            $product->save();

            return ApiResponse::apiResponseData(200, '提交成功');
        } catch (\Exception $e) {
            log::error(date('Y-m-d h:i:s',time()).' 产品表单数据提交失败:'.$e->getMessage());
            return ApiResponse::apiResponseData(400, '提交失败');
        }
    }


    /**
     * 获取产品分类列表页面数据
     */
    public function getProductClassListData()
    {
        $data = request()->input();
        $lists = ProductClassModel::where('deleted_at', 0)
            ->orderBy('sort', 'desc')
            ->paginate($data['pageSize']);

        return ApiResponse::apiResponseData(200, '获取商品分类列表页面数据成功', [
            'lists' => $lists
        ]);
    }


    /**
     * 删除产品分类
     */
    public function productClassDeleteSubmit()
    {
        $class_id = request()->input('id');

        if (ProductModel::where('class_id', $class_id)->count() > 0) {
            return ApiResponse::apiResponseData(400, '该分类下有产品，不能删除');
        }

        $productClass = ProductClassModel::find($class_id);
        $productClass->delete();

        return ApiResponse::apiResponseData(200, '删除成功');
    }


    /**
     * 获取产品分类表单数据
     */
    public function getProductClassFormData()
    {
        $class_id = request()->input('id');

        $lists = [];
        if ($class_id > 0) {
            $lists = ProductClassModel::find($class_id);
        }

        return ApiResponse::apiResponseData(200, '获取商品分类表单数据成功', [
            'lists' => $lists
        ]);
    }


    /**
     * 产品分类表单数据提交
     */
    public function productClassFormSubmit()
    {
        $post = request()->input();

        if (isset($post['id'])) {
            $productClass = ProductClassModel::find($post['id']);
        } else {
            $productClass = new ProductClassModel();
            $productClass->create_time = Carbon::now();
        }
        try {
            $productClass->class_name = $post['class_name'];
            $productClass->save();

           return ApiResponse::apiResponseData(200, '提交成功');
       } catch (\Exception $e) {
           log::error(date('Y-m-d h:i:s',time()).' 产品分类表单数据提交失败:'.$e->getMessage());
           return ApiResponse::apiResponseData(400, '提交失败');
       }
   }

}
